#pragma once

#include <iostream>
#include <string>
#include <vector>
#include <cstring>
#include <cerrno>
#include <math.h>
#include <unistd.h>
#include <sys/fcntl.h>
#include "Log.hpp"
#include "Err.hpp"

namespace Yohifo
{
    // 实用工具包
    struct Util
    {
        static void StringSplit(const std::string &str, const std::string &SEP, int SEP_LEN, std::vector<std::string> &result)
        {
            // 1 + 2
            int start = 0;
            while (start < str.size())
            {
                int pos = str.find(SEP, start);

                if (pos == std::string::npos)
                    break; // 只剩最后一个数字了

                result.push_back(str.substr(start, pos - start));
                start = pos + SEP_LEN;
            }

            if (start < str.size())
                result.push_back(str.substr(start));
        }

        static int StrToInt(const std::string &str)
        {
            // 字符串转为数字
            int n = 0;
            int val = 0; // 10 的次方

            auto rit = str.rbegin();
            while (rit != str.rend())
            {
                n += (*rit - '0') * pow(10, val++);
                ++rit;
            }

            return n;
        }

        static void SetNoBlock(int fd)
        {
            int ret = fcntl(fd, F_GETFL);
            if (ret == -1)
            {
                logMessage(Warning, "SetNoBlock fail %d %s", errno, strerror(errno));
                return;
            }

            fcntl(fd, F_SETFL, ret | O_NONBLOCK);
        }
    };
}